package com.honeycomb.map.control;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.honeycomb.map.service.MapService;
import com.honeycomb.map.service.WechatService;
import com.honeycomb.message.resp.Article;
import com.honeycomb.message.resp.NewsMessage;
import com.honeycomb.message.resp.TextMessage;
import com.honeycomb.utils.MessageUtil;
import com.honeycomb.utils.SHA1;
import com.honeycomb.utils.SystemConstants;

import static com.honeycomb.common.ParamConverter.*;

/**
 * 地图控制器
 * 
 * @author Wangyu
 */
@Controller
@RequestMapping("map/")
public class MapControl {
	
	protected Logger logger = LogManager.getLogger(this.getClass());
	
	@Resource
	private MapService mapService;
	
	@RequestMapping("wechat")
	@ResponseBody
	protected String handleWechatMessage(HttpServletRequest request, HttpServletResponse response) throws IOException {
		response.setCharacterEncoding("UTF-8");
		String method = request.getMethod();
		if(method.equals("GET")){
			if (logger.isDebugEnabled()) {
				logger.debug("GET method received from Wechat:" + request.getRequestURL());
			}
			String signature = request.getParameter("signature");//微信加密签名
			
			String timestamp = request.getParameter("timestamp");//时间戳
			
			String nonce = request.getParameter("nonce");//随机数
			
			String echostr = request.getParameter("echostr");
			
			String[] str = { SystemConstants.WECHAT_TOKEN, timestamp, nonce};
			Arrays.sort(str);//字典排序
			String bigStr = str[0] + str[1] + str[2];
			//SHA1加密
			String digest = new SHA1().getDigestOfString(bigStr.getBytes()).toLowerCase();
			
			//确认请求来至微信
			if(digest.equals(signature)) {
				return echostr;
				//response.getWriter().print(echostr);
			}
			else {
				logger.warn("The signature from WeChat is not equal, received:" + signature + ", expected:" + digest);
				return "error signature";
			}
		}
		else
		if(method.equals("POST")) {
			String respMessage = null;
				//默认返回的文本消息内容
				String respContent = "请求处理异常，请稍后尝试！";
				
				//xml请求解析
				Map<String, String> requestMap = MessageUtil.parseXml(request);
				
				if (logger.isDebugEnabled() ) {
					logger.debug("Get user message from WeChat: " + requestMap);
				}
				
				//发送方账号（open_id）
				String fromUserName = requestMap.get("FromUserName");
				
				//公众账号
				String toUserName = requestMap.get("ToUserName");
				//消息类型
				String msgType = requestMap.get("MsgType");	
				
				//回复文本消息
				TextMessage textMessage = new TextMessage();
				textMessage.setToUserName(fromUserName);
				textMessage.setFromUserName(toUserName);
				textMessage.setCreateTime(new Date().getTime());
				textMessage.setMsgType(MessageUtil.REQ_MESSAGE_TYPE_TEXT);
				textMessage.setFuncFlag(0);
				
				//文本消息
				if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_TEXT)) {
					respContent = "您发送的是文本消息：" + requestMap.get("Content");
				}
				//图片消息
				else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_IMAGE)) {
					respContent = "您发送的是图片消息：" + requestMap.get("PicUrl");
				}
				//地理位置消息
				else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_LOCATION)) {
						double wechatLocationX = convertToDouble(assertNotEmpty(requestMap.get("Location_X")));
						double wechatLocationY = convertToDouble(assertNotEmpty(requestMap.get("Location_Y")));
						
						String distance = "1000m";
						double weiDuX  =  0.0089833;
						double jingDuY  = 0.0114;
						double weiDuMax = wechatLocationX + weiDuX;
						double weiDuMin = wechatLocationX - weiDuX;
						double jingDuMax = wechatLocationY + jingDuY;
						double jingDuMin = wechatLocationY - jingDuY;
						
						 Map<String,String> pictureContent = new WechatService().wechatSelectArticle(weiDuMin, jingDuMin, weiDuMax, jingDuMax);
						 
						 NewsMessage newsMessage = new NewsMessage();
						 newsMessage.setArticleCount(1);
						 Article article = new Article();
						 article.setTitle(pictureContent.get("Title"));
						 article.setDescription(pictureContent.get("Description"));
						 article.setPicUrl("");
						 article.setUrl("");
						 List<Article> list = new ArrayList<Article>();
						 list.add(article);
						 newsMessage.setArticles(list);
						 newsMessage.setToUserName(fromUserName);
						 newsMessage.setFromUserName(toUserName);
						 newsMessage.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_NEWS);
						 newsMessage.setCreateTime(new Date().getTime());
						 
						 respMessage  =  MessageUtil.newsMessageToXml(newsMessage);
						 
						 
					
				}
				//链接消息
				else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_LINK)) {
					respContent = "您发送的是链接消息：" + requestMap.get("Url");
				}
				//音频消息
				else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_VOICE)) {
					respContent = "您发送的是音频消息：";
				}
				//事件推送
				else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_EVENT)) {
					//事件类型
					String eventType = requestMap.get("Event");
					//订阅
					if (eventType.equals(MessageUtil.EVENT_TYPE_SUBSCRIBE)) {
						respContent = "谢谢您的关注。";
					}
					//取消订阅
					else if (eventType.equals(MessageUtil.EVENT_TYPE_UNSUBSCRIBE)) {
						//TOOD 取消订阅后用户再收不到公众账号发送的消息，因此不需要回复。
					}
					//自定义菜单点击事件
					else if (eventType.equals(MessageUtil.EVENT_TYPE_CLICK)) {
						//TOOD 自定义菜单权没有开放，暂不处理该类消息
					}
				}
				
				//textMessage.setContent(respContent);
				//respMessage = MessageUtil.textMessageToXml(textMessage);
				
				if (logger.isDebugEnabled() ) {
					logger.debug("return response message is:" + respMessage);
				}
				
				return respMessage;
//			
//			PrintWriter out = response.getWriter();  
//	        out.print(respMessage);  
//	        out.close();
		}
		else {
			logger.warn("Unexpected request method " + request.getMethod() + "received from " + request.getRequestURL() );
			return "error request method";
		}
	}
}
